package com.atguigu.xuexiplus.service.impl;

import com.atguigu.xuexiplus.dto.UserDTO;
import com.atguigu.xuexiplus.dto.UpdateProfileDTO;
import com.atguigu.xuexiplus.mapper.Usermapper;
import com.atguigu.xuexiplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserserviceImpl implements UserService {
    @Autowired
    private Usermapper userMapper;
    
    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserDTO login(String username, String password) {
        // 先根据用户名查询用户
        UserDTO user = userMapper.findByUsername(username);
        if (user == null) {
            System.out.println("用户不存在: " + username);
            return null;
        }
        
        // 明文密码对比
        if (password.equals(user.getPassword())) {
            // 密码正确，清除密码字段后返回
            user.setPassword(null);
            System.out.println("密码验证成功: " + username);
            return user;
        }
        
        System.out.println("密码错误: " + username);
        return null;
    }
    
    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public UserDTO findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public UserDTO findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public UserDTO updateProfile(UpdateProfileDTO dto) {
        if (dto == null || dto.getUserId() == null) {
            throw new IllegalArgumentException("userId不能为空");
        }
        userMapper.updateProfile(dto.getUserId(), dto.getNickname(), dto.getAvatarUrl());
        UserDTO updated = userMapper.findById(dto.getUserId());
        if (updated != null) {
            updated.setPassword(null);
        }
        return updated;
    }
    /**
     * 更新用户状态
     * @param username
     * @param i
     */
    @Override
    public void updateStatus(String username, int i) {
        userMapper.updateStatus(username, i);
    }

    @Override
    public java.util.List<com.atguigu.xuexiplus.entity.User> listAllUsers() {
        return userMapper.listAllUsers();
    }

}
